package com.pctx.bibaregisterlogin.service.impl;

import com.pctx.bibaregisterlogin.dao.MessageOrderMapper;
import com.pctx.bibaregisterlogin.pojo.MessageOrder;
import com.pctx.bibaregisterlogin.pojo.MessageOrderExample;
import com.pctx.bibaregisterlogin.service.MessageOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by chason on 2018/3/9.18:52
 */
@Service("messageOrderService")
public class MessageOrderServiceImpl implements MessageOrderService {
    @Autowired
    private MessageOrderMapper messageOrderMapper;

    @Override
    public List<MessageOrder> getByUserUuid(String userUuid) throws Exception {
        if (StringUtils.isEmpty(userUuid))
            return null;

        MessageOrderExample example = new MessageOrderExample();
        example.setOrderByClause("create_time desc");
        MessageOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserUuidEqualTo(userUuid);

        return messageOrderMapper.selectByExample(example);
    }

    @Override
    public List<MessageOrder> getByCompanyUuid(String companyUuid) throws Exception {
        if (StringUtils.isEmpty(companyUuid))
            return null;

        MessageOrderExample example = new MessageOrderExample();
        example.setOrderByClause("create_time desc");
        MessageOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserUuidEqualTo(companyUuid);

        return messageOrderMapper.selectByExample(example);
    }

    @Override
    public boolean readMessage(String uuid) throws Exception {
        if (StringUtils.isEmpty(uuid)) {
            return false;
        }

        MessageOrder messageOrder = getByUuid(uuid);
        if (null == messageOrder)
            return false;

        if (1 == messageOrder.getStatus())
            return true;

        messageOrder.setStatus(MessageOrder.STATUS_READ);

        return messageOrderMapper.updateByPrimaryKeySelective(messageOrder) > 0;
    }

    @Override
    public MessageOrder getByUuid(String uuid) throws Exception {
        if (StringUtils.isEmpty(uuid))
            return null;

        MessageOrderExample example = new MessageOrderExample();
        MessageOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUuidEqualTo(uuid).andStatusNotEqualTo(MessageOrder.STATUS_DEL);

        List<MessageOrder> list = messageOrderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list))
            return null;

        return list.get(0);
    }
}
